package com.zhz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhz.domain.User;
import com.zhz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhz.domain.UserBank;
import com.zhz.mapper.UserBankMapper;
import com.zhz.service.UserBankService;
import org.springframework.util.StringUtils;

/**
 * @author ：zhz
 * @date ：Created in 2021/01/02
 * @version: V1.0
 * @slogan: 天下风云出我辈，一入代码岁月催
 * @description:
 **/
@Service
public class UserBankServiceImpl extends ServiceImpl<UserBankMapper, UserBank> implements UserBankService {

    @Autowired
    private UserService userService;
    /**
     * 分页查询银行卡列表
     *
     * @param page   分页参数
     * @param userId 会员的id
     * @return
     */
    @Override
    public Page<UserBank> findByPage(Page<UserBank> page, Long userId) {
        return page(page, new LambdaQueryWrapper<UserBank>()
                .eq(userId != null, UserBank::getUserId, userId));
    }

    /**
     * 查询用户的银行卡
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public UserBank getCurrentUserBank(Long userId) {
        return getOne(new LambdaQueryWrapper<UserBank>()
                .eq(UserBank::getUserId, userId)
                .eq(UserBank::getStatus, 1));
    }

    /**
     * 绑定银行卡
     *
     * @param userId   用户id
     * @param userBank 银行卡信息
     * @return
     */
    @Override
        public boolean bindBank(Long userId, UserBank userBank) {
        // 支付密码的判断
        String payPassword = userBank.getPayPassword();
        User user = userService.getById(userId);
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if(!bCryptPasswordEncoder.matches(payPassword,user.getPaypassword())){
            throw new IllegalArgumentException("用户的支付密码错误") ;
        }
        Long id = userBank.getId();
        if (!StringUtils.isEmpty(id)){//有ID代表是修改操作
            UserBank bank = getById(id);
            if (StringUtils.isEmpty(bank)){
                throw new IllegalArgumentException("用户的银行卡的银行卡的ID输入错误");
            }
            updateById(bank);//修改
        }
        // 若银行卡的id为null ,则需要新建一个
        userBank.setUserId(userId);
        return save(userBank);
    }
}
